#!/usr/local/python3/bin/python3.7
# coding=utf-8
# https://www.cnblogs.com/shiji888/p/12508996.html
import re
from urllib import request
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.RevokeSecurityGroupRequest import RevokeSecurityGroupRequest
from aliyunsdkecs.request.v20140526.AuthorizeSecurityGroupRequest import AuthorizeSecurityGroupRequest


# 获取当前公网ip
def GetCompanyPublicIp():
    req = request.Request('https://ip.cn/')
    # req.add_header('User-Agent', 'curl/7.53.1')   ## 用curl方式请求，会少很多html页面。
    req.add_header('User-Agent',
                   'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
    f = request.urlopen(req)
    ip_str = f.read().decode('utf-8')
    ip = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", ip_str)
    return ip[0]


# 获取历史公网ip
def GetCompanyOldIp():
    try:
        f = open('ip.txt', 'r')
        oldIP = f.read().strip()
        return oldIP
    except IOError:
        print("Error: 没有找到文件或读取文件失败")
    else:
        f.close()


# 写入新的ip到本地
def IputCompanyNewIp(ip):
    try:
        f = open('ip.txt', 'w')
        f.write(ip)
    except IOError:
        print("Error: 没有找到文件或读取文件失败")
    else:
        print("写入NewIp成功")
        f.close() < br >


# 此处分别填写创建的RAM子账号的AccessKeyId，子账号的AccessKeySecret，以及要管理的大区
client = AcsClient('LTAI4F**********94nD4', 'LT8U*************ecc', 'cn-hangzhou')
< br >  # 删除规则


def DelGroup(SourceCidrIp):
    request = RevokeSecurityGroupRequest()
    request.set_accept_format('json')
    request.set_SecurityGroupId("sg-bp***********s1")
    request.set_PortRange("1/65535")
    request.set_IpProtocol("tcp")
    request.set_SourceCidrIp(SourceCidrIp)
    response = client.do_action_with_exception(request)
    request.set_Description("公司出网端口")
    print(str(response, encoding='utf-8'))


# 添加规则
def AddGroup(SourceCidrIp):
    request = AuthorizeSecurityGroupRequest()
    request.set_accept_format('json')
    request.set_SecurityGroupId("sg-bp*********s1")  # 安全组ID
    request.set_IpProtocol("tcp")　　　　　　　　　　　　　　　
    request.set_PortRange("1/65535")
    request.set_Description("公司出网端口")
    request.set_SourceCidrIp(SourceCidrIp)
    response = client.do_action_with_exception(request)
    print(str(response, encoding='utf-8'))


# AddGroup(ip)
if __name__ == '__main__':
    NewIp = GetCompanyPublicIp()
    OldIp = GetCompanyOldIp()
    if NewIp == OldIp:
        print('公司出口ip没有发生变化')
    else:
        print('公司出口ip发生变化：', NewIp)
        IputCompanyNewIp(NewIp)
        DelGroup(OldIp)
        AddGroup(NewIp)